package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.TaskObjectDao;
import com.wlhse.entity.TaskObjectPojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.TaskObjectService;
import com.wlhse.util.SortCodeUtil;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TaskObjectServiceImpl implements TaskObjectService {

    @Resource
    private TaskObjectDao taskObjectDao;

    @Resource
    private SortCodeUtil sortCodeUtil;


    @Override
    public String getTaskObjectByCondition(String taskObjectName, TaskObjectPojo taskObjectPojo) {
        if (taskObjectPojo.getType().equals("all"))
            return NR.r(taskObjectDao.queryTaskObjectByName(taskObjectName, taskObjectPojo.getStatus()));
        int total = taskObjectDao.queryTotal(taskObjectName, taskObjectPojo.getStatus());//数据总数
        PageHelper.startPage(taskObjectPojo.getPageIdx(), taskObjectPojo.getPageSize());
        List<TaskObjectPojo> list = taskObjectDao.queryTaskObjectByName(taskObjectName, taskObjectPojo.getStatus());
        return NR.r(list, total, taskObjectPojo.getPageIdx());
    }

    @Override
    public String getTaskObject(String id) {//根据id查询详情
        TaskObjectPojo list = taskObjectDao.queryTaskObjects(id);
        return NR.r(list);
    }

    @Override
    @Transactional
    public String addTaskObject(TaskObjectPojo taskObjectPojo) {
        String s = taskObjectDao.queryLastCode();
        String code;
        if (StringUtils.isNotBlank(s)) {
            code = sortCodeUtil.getMaxCodeString(s);
        } else {
            code = "0001";
        }
        taskObjectPojo.setTaskObjectCode(code);
        if (taskObjectDao.addTaskObject(taskObjectPojo) <= 0)
            throw new WLHSException("新增失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String removeTaskObject(String id) {
        if (taskObjectDao.deleteTaskObject(id) <= 0)
            throw new WLHSException("删除失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String updateTaskObject(TaskObjectPojo taskObjectPojo) {
        if (taskObjectDao.updateTaskObject(taskObjectPojo) <= 0)
            throw new WLHSException("更新失败");
        return NR.r();
    }
}
